package com.three.digit.model;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import com.three.digit.tools.Utils;

@SuppressWarnings ("rawtypes")
public class PercentHashSet <E extends Comparable> extends HashSet <E>
{
    private static final long serialVersionUID = 1L;

    private int total = 0;
    private HashMap <E, Integer> keyCounter = new HashMap <E, Integer> ();

    @Override
    public boolean add (E e)
    {
        Integer num = keyCounter.get (e);
        if (num == null)
        {
            num = 1;
        }
        else
        {
            num++;
        }
        keyCounter.put (e, num);

        total++;
        return super.add (e);
    }

    public void print ()
    {
        List <String[]> data = getData ();
        for (String[] s : data)
        {
            System.out.println (s[0] + "   " + s[1] + "   " + s[2]);
        }
    }

    public void printAndSaveToFile (String fileName)
    {
        try
        {
            List <String[]> data = getData ();
            for (String[] s : data)
            {
                System.out.println (s[0] + "   " + s[1] + "   " + s[2]);
            }

            Utils.writeMapToExcel (ClassLoader.getSystemResource ("").getPath () + "" + fileName + ".xls", data);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace ();
        }
    }

    @SuppressWarnings ("unchecked")
    public List <String[]> getData ()
    {
        ArrayList <E> temp = new ArrayList <E> ();

        Iterator <E> iterator = iterator ();
        while (iterator.hasNext ())
        {
            E type = (E) iterator.next ();
            temp.add (type);
        }

        Collections.sort (temp);

        NumberFormat defaultFormat = NumberFormat.getPercentInstance ();
        defaultFormat.setMinimumFractionDigits (2);

        List <String[]> data = new ArrayList <String[]> ();
        for (int i = 0; i < temp.size (); i++)
        {
            E e = temp.get (i);
            Integer num = keyCounter.get (e);

            data.add (new String[]
            { e.toString (), num.toString (), defaultFormat.format (num * 1.0 / total) });
        }

        return data;
    }

}
